<!--
 * @Author: 王启萌 2935438217@qq.com
 * @Date: 2022-09-02 08:36:46
 * @LastEditors: 郭招娣 10615594+guo-zhaodi@user.noreply.gitee.com
 * @LastEditTime: 2022-10-07 16:48:09
 * @FilePath: \甲方\hello-world\src\views\House.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<template>
  <div class="house">
    <div>
      <input v-model="inputVal" @keydown="sendText" />
    </div>
    <div class="websocket"></div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
const inputVal = ref('')
let ws = null

const initSocket = () => {
  ws.onopen = socketOpen
  ws.onmessage = socketMessage //onmessage 响应后端的send
}
const socketMessage = Data => {
  let { text } = JSON.parse(Data.data) //将其他客户端发送的消息转为对象 ==> 将text解构
  console.log(Data)
  const websocket = document.querySelector('.websocket')
  websocket.innerHTML += `<div>
                                <h4>${new Date().toLocaleString()}</h4>
                                <p>${text}</p>
                            </div>`
}
const sendText = e => {
  if (e.keyCode == '13') {
    const websocket = document.querySelector('.websocket')
    //将输入的内容显示在当前客户端
    websocket.innerHTML += `<div>
        <h4>${new Date().toLocaleString()}</h4>
        <p>${inputVal.value}</p>
    </div>`
    //往后端发送消息
    ws.send(
      JSON.stringify({
        text: inputVal.value,
      })
    )
    inputVal.value = '' //清空文本框
  }
}

const socketOpen = () => {
  if (ws.readyState === 1) {
    console.log('连接成功')
  }
}
onMounted(() => {
  let url = 'ws://localhost:8888'
  ws = new WebSocket(url) //初始化ws ==> 将后端地址传入到socket中
  initSocket() //初始化socket方法
})
</script>
<style lang="scss">
.house {
  height: 600px;
  input {
    width: 300px;
    height: 30px;
  }
}
@media screen and (max-width: 400px) {
  .house {
    height: 600px;
    input {
      height: 50px;
    }
  }
}
</style>
